package com.zzyl.nursing.service.impl;

import java.beans.Expression;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author wgy
 * @date 2025-01-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //判断老人是否入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));

        //如果老人不为空，则老人已经入住，无需添加
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住");
        }

        //修改床位信息
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //新增老人信息
        elder = insertAndUpdateElder(bed, checkInApplyDto);

        //新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);

        //新增签约信息
        String contrastNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(elder, contrastNo, checkInApplyDto);

        //新增入住配置
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);

    }

    /**
     * 新增入住配置
     * @param id
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {
        //创建入住配置对象
        CheckInConfig checkInConfig = new CheckInConfig();
        //拷贝属性
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);

        //新增入住配置
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /**
     * 新增签约信息
     * @param elder
     * @param contrastNo
     * @param checkInApplyDto
     */
    private void insertContract(Elder elder, String contrastNo, CheckInApplyDto checkInApplyDto) {
        //创建签约对象
        Contract contract = new Contract();
        //拷贝属性
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contrastNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());

        //根据合同中的开始时间设置签约状态，如果大于当前时间则生效，小于当前时间未生效
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStatus(startDate.isAfter(LocalDateTime.now()) ? 1 : 0);
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);

        //新增签约信息
        contractMapper.insertContract(contract);
    }

    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        //创建入住对象
        CheckIn checkIn = new CheckIn();
        //拷贝属性
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto
                .getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        //新增入住信息
        save(checkIn);
        return checkIn;
    }

    /**
     * 新增老人信息
     * @param bed
     * @param checkInApplyDto
     * @return
     */
    private Elder insertAndUpdateElder(Bed bed, CheckInApplyDto checkInApplyDto) {
        //创建老人对象
        Elder elder = new Elder();
        //拷贝属性
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        //判断老人是否存在，如果已经入住则修改，如果未入住则新增
        Elder elderDb = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, elder.getIdCardNo()));

        if (ObjectUtils.isNotEmpty(elderDb)) {
            //老人已经存在
            elderMapper.updateById(elder);
        } else {
            elderMapper.insert(elder);
        }

        return elder;
    }


    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        //查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        //根据出生日期计算年龄
        int age = Period.between(LocalDate.parse(elder.getBirthday(), DateTimeFormatter.ofPattern("yyyy-MM-dd")), LocalDate.now()).getYears();
        checkInElderVo.setAge(age);

        //查询老人家属信息
        //TODO 查询家人信息

        //查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());


        //查询签约信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId()));

        //创建vo对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //拷贝属性
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class));

        return checkInDetailVo;
    }
}
